package com.tuotu.gps.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;


import com.tuotu.gps.RecordActivity2;
import com.tuotu.gps.entity.LocationEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

/**
 * Created by apple on 17/6/1.
 */

public class GpsLocationUtils implements LocationListener, GpsStatus.Listener {
    private Context context;
    private LocationManager mLocationMng;
    private Location mLocation;
    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
    SimpleDateFormat sDateFormat2 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    SimpleDateFormat dirFormat = new SimpleDateFormat("yyyy_MM_dd");//设置日期格式
    private setStatusListener setStatusListener;
    private GpsStatus mGpsStatus;
    private ArrayList<LocationEntity> list;
    private int mSatelliteCount;

    private String testPath = "/mnt/sdcard/gps/";

    private volatile boolean needUploadPath;


    static private GpsLocationUtils instance;

    static public GpsLocationUtils getInstance(Context context) {
        if (instance == null) {
            instance = new GpsLocationUtils(context);
        }

        return instance;
    }

    public void onStatusListener(setStatusListener setStatusListener) {
        this.setStatusListener = setStatusListener;
    }

    public boolean isNeedUploadPath() {
        return needUploadPath;
    }

    public void setNeedUploadPath(boolean needUploadPath) {
        this.needUploadPath = needUploadPath;
    }

    public int getSatelliteCount(){
        return mSatelliteCount;
    }

    @Override
    public void onGpsStatusChanged(int status) {
//        LogUtil.print("GpsLocationUitls  onGpsStatusChanged " + "status:" + status);
        if (status == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mGpsStatus = mLocationMng.getGpsStatus(mGpsStatus);
            int maxSatellite = mGpsStatus.getMaxSatellites();
            Iterator<GpsSatellite> it = mGpsStatus.getSatellites().iterator();
            int count = 0;
            while (it.hasNext() && count <= maxSatellite) {
                GpsSatellite s = it.next();
                if (s.usedInFix()) {
                    count++;
                }
            }
//            LogUtil.print("GpsLocationUitls  onGpsStatusChanged " + "count:" + count);
            mSatelliteCount=count;
        }
    }

    public interface setStatusListener {
        void setGpsCount(int count);
        void showChangedialog();
    }


    private GpsLocationUtils(Context context) {
        this.context = context;
        mLocationMng = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    public GpsStatus getmGpsStatus() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        return mLocationMng.getGpsStatus(mGpsStatus);
    }

    public boolean beginUpdateLocation() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        mLocationMng.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        mLocationMng.addGpsStatusListener(this);
        list=new ArrayList<>();
        return true;
    }

    public boolean stopUpdateLocation() {
        mLocationMng.removeUpdates(this);
        return true;
    }

    public Location getLastLocation() {
//        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
//                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            return null;
//        }
//        return mLocationMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        return mLocation;
    }

    public void saveFile(final String userId){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
//                        LocationEntity entity=new LocationEntity(sDateFormat.format(new Date()),111.1,22.2,0,(float) 135.4);
//                        ArrayList<LocationEntity> tem=new ArrayList<LocationEntity>();
//                        tem.add(entity);
                        Date date=new Date();
                        if(null!=list&&list.size()>0){
                            LogUtil.print("GpsLocationUtils saveFile -- "+list.size()+"==needUploadPath=="+needUploadPath);
                            if(needUploadPath){
                                Utils.saveLocationEntity(RecordActivity2.GPS_DIR+dirFormat.format(date)+"/"+sDateFormat2.format(date)+".txt",list);
                            }
                        }else {
                            LogUtil.print("GpsLocationUtils null!=list&&list.size()>0 --false ");
                        }
                        list.clear();
                        LogUtil.print("GpsLocationUtils list.clear() -- ");

                        new CollectionUploadPathFile(context,userId);//上传轨迹

                        setNeedUploadPath(false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLocation = location;
        if (null != location) {
            try {
                long mTime =  location.getTime();
                double mlon = location.getLongitude();
                double mlat =  location.getLatitude();
                float mSpeed =  location.getSpeed();
                float mDirect =  location.getBearing();
                LocationEntity entity=new LocationEntity(sDateFormat.format(new Date(mTime)),mlon,mlat,mDirect,mSpeed);
                list.add(entity);
//            Log.i("xyw", "-c-time=" + location.getTime());
//            Log.i("xyw", "-c-lon=" + location.getLongitude());
//            Log.i("xyw", "-c-lat=" + location.getLatitude());
//            Log.i("xyw", "-c-speed=" + location.getSpeed());
//            Log.i("xyw", "-c-mDirect=" + location.getBearing());
            } catch (Exception e) {
                LogUtil.print("get location error"+e.toString());
            }
        } else {
            LogUtil.print("location===null");
        }
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
//        LogUtil.print("GpsLocationUitls  onStatusChanged "+provider+"status:"+status);
//        Utils.createGpsInfo(provider+"status:"+status,testPath);
//        setStatusListener.onStatusChanged(status);
    }

    @Override
    public void onProviderEnabled(String provider) {
        LogUtil.print("GpsLocationUitls gps onProviderEnabled");
    }

    @Override
    public void onProviderDisabled(String provider) {
        LogUtil.print("GpsLocationUitls gps onProviderDisabled");
        Toast.makeText(context,"GPS模块未打开，请去设置界面设置位置信息为高精度模式",Toast.LENGTH_SHORT).show();
        setStatusListener.showChangedialog();
    }


}
